import pymysql
from config import config
from password_utils import decrypt_password

class DatabaseConnection:
    """数据库连接工具类，提供统一的数据库连接方法"""
    
    @staticmethod
    def create_connection(db_config=None):
        """
        创建数据库连接
        
        Args:
            db_config: 数据库配置对象，如果为None则使用配置文件中的默认配置
            
        Returns:
            pymysql.Connection: 数据库连接对象
        """
        if db_config is None:
            # 使用配置文件中的默认配置
            host = config.get("database.host", "localhost")
            port = config.get("database.port", 3306)
            database = config.get("database.database", "ssm")
            username = config.get("database.username", "root")
            # 支持密码为明文或密文（ENC: 开头）
            raw_password = config.get("database.password")
        else:
            # 使用传入的配置对象
            host = db_config.host
            port = db_config.port
            database = db_config.database
            username = db_config.username
            raw_password = db_config.password
        
        # 解密密码（如为密文）；如果是明文则原样返回
        password = decrypt_password(raw_password)
        
        # 确保参数类型正确
        if isinstance(port, dict):
            port = port.get("value", 3306)
        port = int(port)
        
        # 统一的数据库连接参数
        connection = pymysql.connect(
            host=str(host),
            port=port,
            user=str(username),
            password=str(password),
            database=str(database),
            charset='utf8mb4'
        )
        
        return connection
    
    @staticmethod
    def get_connection_url(db_config=None):
        """
        获取数据库连接URL（用于调试和日志）
        
        Args:
            db_config: 数据库配置对象
            
        Returns:
            str: 数据库连接URL
        """
        if db_config is None:
            host = config.get("database.host", "localhost")
            port = config.get("database.port", 3306)
            database = config.get("database.database", "ssm")
            username = config.get("database.username", "root")
        else:
            host = db_config.host
            port = db_config.port
            database = db_config.database
            username = db_config.username
        
        if isinstance(port, dict):
            port = port.get("value", 3306)
        
        return f"mysql://{username}@{host}:{port}/{database}"